#include <algorithm>
#include <iostream>
#include <stack>
#include <string>
using namespace std;

/**
 * @方法: 栈
 * @时间复杂度: o()
 * @空间复杂度: o()
 * @评价:
 */
char st[2005];
int top;
string reverseParentheses(string s) {
    for (int i = 0; i < s.length(); i++) {
        if (s[i] != ')')
            st[top++] = s[i];
        else {
            string str="";
            while(st[top-1] != '('){
                str += st[--top];
            }
            --top;
            for(int j=0;j<str.length();j++){
                st[top++] = str[j];
            }
        }
    }
    string ans = "";
    for(int i=0;i<top;i++) ans += st[i];
    return ans;
}


/**
 * @方法: 模拟
 * @时间复杂度: o()
 * @空间复杂度: o()
 * @评价:
 */
string reverseParentheses1(string s) {
    if (s.find('(') == string::npos) return s;
    if (s.find('(') == 0 && s.find(')') == s.length() - 1) {
        reverse(s.begin(), s.end());
        return s.substr(1, s.length() - 2);
    }
    string ans;
    int left = s.find('(');
    int right = -1;
    while (left != string::npos) {
        ans += s.substr(right + 1, left - right - 1);
        int cnt = 0;
        for (int i = left + 1; i < s.length(); i++) {
            if (s[i] == ')' && cnt == 0) {
                right = i;
                break;
            } else if (s[i] == ')')
                cnt--;
            else if (s[i] == '(')
                cnt++;
        }
        string tmp = s.substr(left + 1, right - left - 1);
        tmp = reverseParentheses(tmp);
        reverse(tmp.begin(), tmp.end());
        ans += tmp;
        left = s.find('(', right + 1);
    }
    if (right != s.length() - 1)
        ans += s.substr(right + 1, s.size() - right - 1);
    return ans;
}

int main() {
    string s = "(abcd)";
    string ans = reverseParentheses(s);
    cout << ans << endl;
    return 0;
}